<template>
  <draggable
    v-bind="dragOptions"
    tag="div"
    class="drag-container"
    :list="list"
    item-key="id"
    @start="handleDragStart"
    @end="handleDragEnd"
    @update:modelValue="emitter"
  >
    <template #item="{ element }">
      <div 
        :key="element.id" 
        class="drag-group"
        :style="{ 
          transition: isDragging ? 'none' : 'all 0.3s ease',
          transform: isDragging ? 'none' : (element.transform || 'none')
        }"
        ref="groupRefs"
      >
        <!-- 拖拽项主体 -->
        <div class="drag-item">
          <span class="drag-handle">☰</span>
          <ImgRender :style="{width:'23px',height:'23px',border:'1px solid #ccc',borderRadius:'10%',marginRight:'10px'}" :url="$globalSetting.value.iconPath+'\\'+element.icon" />
          <span class="drag-item__name">{{ element.name }}</span>
          <!-- 添加右侧三个点按钮 -->
          
          <el-dropdown trigger="click" @command="handleOption">
            <button 
            class="more-options" 
            >
              ⋮
            </button>
            <template #dropdown>
            <el-dropdown-menu>
                <el-dropdown-item :command="{ type: 'edit',...element}">Edit</el-dropdown-item>
                <el-dropdown-item :command="{ type: 'delete',...element}">Delete</el-dropdown-item>
            </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 子容器过渡组件 -->
        <transition 
          name="nested-fade"
          @before-enter="() => handleBeforeChildEnter(element)"
          @after-enter="() => handleAfterTransition(element)"
          @before-leave="() => handleBeforeChildLeave(element)"
          @after-leave="() => handleAfterTransition(element)"
        >
          <!-- 修复子容器显示条件 -->
          <nested-draggable
            v-show="shouldShowChild(element)" 
            class="drag-nested"
            :is-top-level="false"
            :isShow="false"
            :show2="false"
            :list="element.elements || []" 

            @update:modelValue="updateChildList(element.id, $event)"
            @item-options="handleNestedItemOptions"
            @update-item="handleUpdateNestedItem(element.id, $event)"
          />
           <!--            @show="$emit('show')"
            @show2="$emit('show2')"
            @close="$emit('close')" -->
        </transition>
      </div>
    </template>
  </draggable>
</template>

<script setup lang="ts">
// @ts-nocheck  // 此行会忽略当前组件所有TS错误
import { ref, onMounted, nextTick,getCurrentInstance } from "vue";
import draggable from "vuedraggable";
import nestedDraggable from "./nestedDraggable.vue";
import { ElMessage } from "element-plus";

// 定义 Props
const props = withDefaults(
  defineProps<{
    list: Array<{
      id: number;
      name: string;
      elements: Array<{ id: number; name: string; elements: any[] }>;
      transform?: string;
    }>;
    isTopLevel: boolean;
    isShow: boolean;
    show2: boolean;
  }>(),
  {
    isTopLevel: false,
    isShow: false,
    show2: false
  }
);
//const $globalProperties=getCurrentInstance()?.appContext.config.globalProperties;
// 定义 Emits
const emit = defineEmits<{
  (e: "update:modelValue", value: typeof props.list): void;
  (e: "show"): void;
  (e: "close"): void;
  (e: "show2"): void;
  (e: "item-options", data: {id: number; name: string; depth: number; parentId?: number}): void;
  (e: "update-item", data: {id: number; name: string; parentId?: number}): void;
}>();

// 响应式状态
const targetIndex = ref(-1);
const isDragging = ref(false);
const groupRefs = ref<HTMLDivElement[]>([]);
const elementHeights = ref<Record<number, number>>({});

// 计算当前层级深度
const depth = props.isTopLevel ? 1 : 2;

// 拖拽配置
const dragOptions = {
  animation: 200,
  group: "description",
  disabled: false,
  ghostClass: "drag-ghost",
  draggingClass: "drag-active",
  handle: ".drag-handle",
};

// 修复子容器显示条件逻辑
const shouldShowChild = (element: typeof props.list[0]) => {
  if (props.show2) return false;
  if (targetIndex.value === element.id) return false;
  if (!props.isShow && element.elements.length === 0) return false;
  return true;
};

// 处理拖拽开始
const handleDragStart = (e: any) => {
  isDragging.value = true;
  const element = props.list[e.oldIndex];
  
  if (element.elements.length < 1) {
    emit('show');
    targetIndex.value = element.id;
  } else {
    emit('show2');
  }
  
  recordElementHeights();
};

// 处理拖拽结束
const handleDragEnd = () => {
  emit('close');
  targetIndex.value = -1;
  
  setTimeout(() => {
    isDragging.value = false;
    adjustElementPositions();
  }, 200);
};

// 记录元素高度
const recordElementHeights = () => {
  nextTick(() => {
    groupRefs.value.forEach((el, index) => {
      if (el && props.list[index]) {
        elementHeights.value[props.list[index].id] = el.offsetHeight;
      }
    });
  });
};

// 处理子容器进入前
const handleBeforeChildEnter = (element: typeof props.list[0]) => {
  if (isDragging.value) return;
  recordElementHeights();
};

// 处理子容器离开前
const handleBeforeChildLeave = (element: typeof props.list[0]) => {
  if (isDragging.value) return;
  recordElementHeights();
};

// 处理过渡完成后
const handleAfterTransition = (element: typeof props.list[0]) => {
  if (isDragging.value) return;
  
  adjustElementPositions();
  
  const updatedList = props.list.map(el => {
    if (el.id === element.id) {
      return { ...el, transform: '' };
    }
    return el;
  });
  emitter(updatedList);
};

// 修复位置调整逻辑
const adjustElementPositions = () => {
  nextTick(() => {
    let cumulativeOffset = 0;
    const updatedList = [...props.list];
    
    updatedList.forEach((element, index) => {
      const refElement = groupRefs.value[index];
      if (!refElement) return;
      
      const currentHeight = refElement.offsetHeight;
      const previousHeight = elementHeights.value[element.id] || currentHeight;
      const heightDiff = currentHeight - previousHeight;
      
      if (index > 0) {
        cumulativeOffset += heightDiff;
        element.transform = `translateY(${cumulativeOffset}px)`;
      }
    });
    
    emitter(updatedList);
  });
};

// 向父组件同步列表数据
const emitter = (value: typeof props.list) => {
  emit("update:modelValue", value);
};

// 递归更新深层子项
const updateChildListRecursive = (
  elements: typeof props.list,
  parentId: number,
  updatedList: typeof props.list
) => {
  return elements.map((el) => {
    if (el.id === parentId) {
      return { ...el, elements: updatedList };
    }
    if (el.elements?.length) {
      return { ...el, elements: updateChildListRecursive(el.elements, parentId, updatedList) };
    }
    return el;
  });
};

// 同步子层级列表
const updateChildList = (parentId: number, updatedList: typeof props.list) => {
  const updatedElements = props.list.map((el) => {
    if (el.id === parentId) {
      return { ...el, elements: updatedList };
    }
    if (el.elements?.length) {
      return { ...el, elements: updateChildListRecursive(el.elements, parentId, updatedList) };
    }
    return el;
  });
  emitter(updatedElements);
  
  nextTick(() => {
    adjustElementPositions();
  });
};

// 递归更新单个子项
const updateItemRecursive = (
  elements: typeof props.list,
  itemId: number,
  updatedData: Partial<typeof props.list[0]>,
  parentId?: number
) => {
  return elements.map((el) => {
    if (el.id === itemId) {
      // 找到匹配的项，更新数据
      return { ...el, ...updatedData };
    }
    if (el.elements?.length) {
      // 递归更新子项
      const updatedChildren = updateItemRecursive(el.elements, itemId, updatedData, el.id);
      return { ...el, elements: updatedChildren };
    }
    return el;
  });
};

// 处理更新当前层级的项
const updateCurrentItem = (itemId: number, updatedData: Partial<typeof props.list[0]>) => {
  try{
    const updatedElements = updateItemRecursive(props.list, itemId, updatedData);
    emitter(updatedElements);
    ElMessage.success("更新成功");}
  catch(err){
    ElMessage.error("更新失败"+err)
  }
};

// 处理嵌套组件的项更新
const handleUpdateNestedItem = (parentId: number, data: {id: number; name: string}) => {
  // 更新当前层级中的子项
  updateCurrentItem(data.id, { name: data.name });
  
  // 将更新事件向上传递
  emit('update-item', {
    id: data.id,
    name: data.name,
    parentId
  });
};

// 处理三点按钮点击事件
/* const handleMoreOptionsClick = (element: typeof props.list[0]) => {
  emit('item-options', {
    id: element.id,
    name: element.name,
    depth: depth
  });
}; */

// 处理嵌套组件传递的选项事件
const handleNestedItemOptions = (data: {id: number; name: string; depth: number; parentId?: number}) => {
  emit('item-options', {
    ...data,
    depth: data.depth + 1,
    parentId: data.parentId || undefined
  });
};
const handleOption=({type,...rest}: any)=>{
  
  if (type==='edit') {
    //console.log(rest)
    emit('item-options',{...rest})
  }
  else{
    confirmDelete(rest)
  }
}
const confirmDelete = (data:any) => {
  ElMessageBox.confirm(
    'This attack will be deleted. Continue?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      try{
      // 1. 递归删除当前列表中的目标项（data.id 是要删除的项 ID）
      const updatedList = deleteItemRecursive(props.list, data.id);
      
      // 2. 同步更新父组件列表（通过 emitter 触发 update:modelValue）
      emitter(updatedList);
       ElMessage.success('Deleted successfully');
      //emit('item-delete',data)
      }catch(err){
        ElMessage.error('Deleted failed'+err);
      }
    })

}
const deleteItemRecursive = (
  elements: typeof props.list,
  targetId: number
): typeof props.list => {
  return elements.filter((el) => {
    // 1. 过滤掉当前层级中 ID 匹配的目标项（不保留）
    if (el.id === targetId) {
      return false;
    }
    // 2. 若当前项有子列表，递归处理子列表（删除子列表中的目标项）
    if (el.elements?.length) {
      el.elements = deleteItemRecursive(el.elements, targetId);
    }
    // 3. 保留非目标项
    return true;
  });
};

onMounted(() => {
  nextTick(() => {
    recordElementHeights();
  });
});

// 提供更新项的方法给父组件调用
defineExpose({
  updateItem: updateCurrentItem
});
</script>

<style scoped>
/* 样式保持不变 */
.drag-container {
  box-sizing: border-box;
  width: 100%;
  padding: 1rem;
  margin: 0 auto;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: box-shadow 0.2s ease;
}

.drag-container:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.drag-group {
  margin-bottom: 0.8rem;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.drag-group:last-child {
  margin-bottom: 0;
}

.drag-item {
  display: flex;
  align-items: center;
  padding: 0.4rem 1rem;
  background-color: #f9fafb;
  border: 1px solid #f0f1f2;
  border-radius: 6px;
  cursor: default;
  transition: 
    background-color 0.2s ease,
    border-color 0.2s ease,
    box-shadow 0.2s ease,
    transform 0.2s ease;
}

.drag-item:hover {
  background-color: #f3f4f6;
  border-color: #e5e7eb;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transform: translateY(-1px);
}

.drag-handle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.5rem;
  height: 1.5rem;
  margin-right: 0.8rem;
  color: #9ca3af;
  cursor: move;
  border-radius: 4px;
  transition: color 0.2s ease, background-color 0.2s ease, transform 0.2s ease;
}

.drag-handle:hover {
  color: #4b5563;
  background-color: #e5e7eb;
  transform: scale(1.1);
}

.drag-item__name {
  font-size: 0.95rem;
  color: #1f2937;
  line-height: 1.4;
  flex: 1;
}

.more-options {
  background: none;
  border: none;
  color: #9ca3af;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-options:hover {
  color: #4b5563;
  background-color: #e5e7eb;
  transform: scale(1.1);
}

.more-options:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.drag-nested {
  margin-top: 3px;
  box-sizing: border-box;
  padding: 0.6rem 1.2rem 0.6rem 1.2rem;
  border-left: 1px dashed #e5e7eb;
  transition: all 0.3s ease;
  overflow: hidden;
}

.drag-ghost {
  padding: 0.8rem 1rem;
  margin-bottom: 0.8rem;
  background-color: #eff6ff;
  border: 1px dashed #93c5fd;
  border-radius: 6px;
  opacity: 0.8;
  transition: all 0.2s ease;
}

.drag-active .drag-item {
  background-color: #eff6ff;
  border-color: #93c5fd;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
  transform: scale(1.01);
}

.drag-active .drag-handle {
  color: #3b82f6;
}

.nested-fade-enter-active,
.nested-fade-leave-active {
  transition: all 0.3s ease-out;
}

.nested-fade-enter-from {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
  padding-top: 0;
  padding-bottom: 0;
}

.nested-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  margin-top: 0;
}

@media (max-width: 768px) {
  .drag-container {
    padding: 0.8rem;
  }
  
  .drag-item {
    padding: 0.4rem 0.9rem;
  }
  
  .drag-nested {
    margin-left: 1rem;
    padding-left: 1rem;
  }
  
  .drag-item__name {
    font-size: 0.9rem;
  }
}
</style>

